<?php


namespace app\agent\controller;

use app\admin\model\Assistant;
use app\admin\model\halt\Cate;
use app\admin\model\Admin;
use app\common\model\SerialLog;
use EasyWeChat\Factory;
use app\common\library\Auth;
use \app\common\model\Serial as Serials;
use fast\Http;
use PHPExcel;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Db;
use think\Env;

class Serial extends \app\common\controller\Manage
{
    protected $noNeedLogin = ['config','oauth','login','testlogin','add','download'];
    protected $noNeedRight = ['*'];
    protected $app = '';
    protected $appconfig = '';
    protected $ModelMan;
    protected $modelLog;
    protected $contollerName = 'Serial';
    public function _initialize()
    {
        $this->appconfig = $this->config();
        $this->app = Factory::work($this->config());
        $this->auth = Auth::instance();
        $this->model = new Serials;
        $this->modelLog = new SerialLog();
        parent::_initialize();
    }

    public function testlogin()
    {
        $this->auth->IndexLogin('yangliu');
        return $this->redirect('index');
    }

    public function index()
    {
        if ($this->request->isAjax())
        {
            $this->searchFields = 'text';
            list($where, $sort, $order,$offset, $limit) = $this->buildparams();
            $total = $this->modelLog
                ->where($where)
                ->order('id desc')
                ->count();
            $list = $this->modelLog
                ->where($where)
                ->order('id desc')
                ->paginate($this->request->request('Pagesize',10),false,['query'=>request()->param()]);
            foreach ($list as &$value)
            {
                $value['createtime'] = date('Y-m-d H:i:s',$value->createtime);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('search',$this->request->request('search',''));
        return $this->view->fetch();
    }

    public function add()
    {
        if($this->request->isPost())
        {
            $row = $this->request->request('row/a');
            if(!$row['product'] || !$row['kemu'] || !$row['banben'])
            {
                $this->error('请选择产品分类');
            }
            if($row['number'] < 1 || !$row['number'] || $row['number'] > 100000)
            {
                $this->error('请填写大于0的数量,或数量不要大于10万');
            }
            $banben = Cate::get($row['banben']);
            $product = Cate::get($row['product']);
            $kemu = Cate::get($row['kemu']);
            $data = [];
            for ($i=1;$i<=$row['number'];$i++)
            {
                $data[$i] = [
                    'code'=>'2'.$this->random(12),
                    'product'=>$banben->product,
                    'kemu'=>$banben->kemu,
                    'banben'=>$banben->banben,
                    'type'=>$row['product'].','.$row['kemu'].','.$row['banben'],
                ];
            }
            Db::startTrans();
            try{
                $count = ceil(count($data) / 10);
                for ($i=1;$i<=$count;$i++){
                    $offset=($i -1)*(10);
                    $array=array_slice($data,$offset,10);
                    $this->model->saveAll($array);
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('数据重复','',$e->getMessage());
            }
            //保存到企业微信
            if(!$this->export($data,$this->auth->userid,5000,$name = $product->name.$kemu->name.$banben->name))
            {
                // 回滚事务
                Db::rollback();
                $this->error('企业微信发送失败！');
            }
            // 提交事务
            Db::commit();
            $this->success('序列号生成成功，请打开企业微信小助手查看文件！','/agent/serial/index');
        }
        return $this->view->fetch();
    }

    /**
     * 生产序列号
     * @param $length
     * @param string $chars
     * @return string
     */
    public function random($length, $chars = '01234567893216549870') {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }


    public function download($id=null)
    {
        $config = Assistant::config();
        $app = Factory::work($config);
        $row = $this->modelLog->get($id);
        //更新时间大于3天 重新上传
        if($row->updatetime+259200 < time())
        {
            $path = ROOT_PATH . 'public'.$row->url;
            $res = $app->media->uploadFile($path);
            //发送文件给操作人
            if($res['errcode'] == 0 ){
                $row->media_id = $res['media_id'];
                $row->save();
            }
        }
        $token = $app->access_token->getToken();//获取企业微信token
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
        $params = [
            'touser'=>$this->auth->userid,
            'msgtype'=>'file',
            'agentid'=>$config['agent_id'],
            'file'=>[
                'media_id'=>$row['media_id']
            ],
            'safe'=>0
        ];
        $response = \fast\Http::post($url,json_encode($params));

        $this->success('请打开企业微信小助手查看文件');
    }

    public function export(array $list,$userid = null,$limit=1000,$name='')
    {
        $objPHPExcel = new PHPExcel();
        $count = ceil(count($list) / $limit);
        $row = $objPHPExcel->setactivesheetindex(0);
        //列为文本
        $row->getStyle('A')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        for ($i=1;$i<=$count;$i++){
            $row->setTitle("$i");
            $offset = ($i-1)*($limit);
            $array = array_slice($list,$offset,$limit);
            foreach ($array as $k => $v) {
                $newkeyStr= substr($v['code'], 0, 3);
                $newkey= $newkeyStr . '- ' . substr($v['code'], 3, 5). '- ' . substr($v['code'], 8);
                $row->setcellvalue('A'.($k+1), ''.$newkey.'');
                unset($newkeyStr,$newkey);
                $row->getColumnDimension('A')->setWidth(30);
            }
            if($i <= $count-1)
            {
                //创建一个新的工作空间(sheet)
                $objPHPExcel->createSheet();
                $row = $objPHPExcel->setactivesheetindex($i);
                $row->setTitle("$i");
                //列为文本
                $row->getStyle('A')->getNumberFormat()
                    ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
            }
        }
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-d H-i-s',time());
        $filename = $this->auth->username.'-'.$name.'-'.$date.'.xlsx';
        $objWriter->save('./agent/xlsx/'.$filename);
        //添加操作日志
        $data = [
            'text' => $this->auth->username.'生成'.$name.'/'.count($list).'个',
            'url' => '/agent/xlsx/'.$filename,
        ];
        //上传到企业微信临时文件
        if($userid)
        {
            $config = Assistant::config();
            $app = Factory::work($config);
            $path = ROOT_PATH . 'public/agent/xlsx/'.$filename;
            $res = $app->media->uploadFile($path);
            //发送文件给操作人
            if($res['errcode'] == 0 ){
//                unlink($path);
                $token = $app->access_token->getToken();//获取企业微信token
                $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
                $params = [
                    'touser'=>$userid,
                    'msgtype'=>'file',
                    'agentid'=>$config['agent_id'],
                    'file'=>[
                        'media_id'=>$res['media_id']
                    ],
                    'safe'=>0
                ];
                $response = \fast\Http::post($url,json_encode($params));
                $data['media_id'] = $res['media_id'];
                $data['text'] .='发送给'.$this->auth->username;
                $response = json_decode($response,true);
            }
            serialLog::create($data);
        }
        return true;
    }

    private  function config()
    {
        $config = [
            'agent_id' => Env::get('serial.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('serial.secret'),
            'response_type' => Env::get('serial.response_type'),
            'log' => [
                'level' => Env::get('serial.level'),
                'file' => __DIR__.Env::get('serial.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('serial.scopes'),
                'callback' => Env::get('serial.callback')
            ]
        ];
        return $config;
    }

    public function oauth()
    {
        $token = $this->app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    return redirect('/agent/Serial/index');
                }
            }
        }else{
            return redirect($this->request->domain().'/agent/Serial/index');
        }
    }

    public function login()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appconfig['corp_id']."&redirect_uri=".$this->appconfig['oauth']['callback']."&response_type=code&scope=".$this->appconfig['oauth']['scopes']."&agentid=".$this->appconfig['agent_id']."&state=1#wechat_redirect";
        return redirect($url);
    }

}